// 数据模型
let currentQuiz = {
    questions: [],
    answers: [],
    currentQuestionIndex: 0
};

let userQuizRecord = {
    dailyAttempts: 3,
    lastAttemptDate: '',
    correctCount: 0,
    totalCount: 0,
    wrongQuestions: []
};

const QuizBank = {
    allQuestions: [],

    // 加载指定分类的题库
    loadQuestions: async function (categories) {
        try {
            const allQuestions = [];
            for (const category of categories) {
                const response = await fetch(`./${category}-questions.json`);
                if (!response.ok) {
                    throw new Error(`加载分类 ${category} 题库失败: ${response.statusText}`);
                }
                const questions = await response.json();
                allQuestions.push(...questions);
                console.log(`成功加载 ${category} 分类题库，共 ${questions.length} 道题`);
            }
            this.allQuestions = allQuestions;
            return allQuestions.length > 0;
        } catch (error) {
            console.error(`加载题库失败:`, error);
            throw error;
        }
    },

    // 获取随机题目（默认3题）
    getRandomQuestions: function (count = 3) {
        if (this.allQuestions.length === 0) throw new Error('题库为空，请先加载题库');
        const availableCount = Math.min(count, this.allQuestions.length);
        return [...this.allQuestions].sort(() => 0.5 - Math.random()).slice(0, availableCount);
    },

    // 根据ID获取题目
    getQuestionById: function (id) {
        return this.allQuestions.find(q => q.id === id);
    },

    // 获取题库中题目的总数
    getTotalQuestionsCount: function () {
        return this.allQuestions.length;
    }
};

// 辅助函数
function showLoading(message = '加载中...') {
    const loading = document.getElementById('loading');
    const loadingMessage = document.getElementById('loading-message');
    loadingMessage.textContent = message;
    loading.classList.remove('hidden');
    setTimeout(() => {
        loading.querySelector('div').classList.remove('opacity-0');
        loading.querySelector('div').classList.add('opacity-100');
    }, 10);
}

function hideLoading() {
    const loading = document.getElementById('loading');
    loading.querySelector('div').classList.remove('opacity-100');
    loading.querySelector('div').classList.add('opacity-0');
    setTimeout(() => {
        loading.classList.add('hidden');
    }, 300);
}

// 用户记录管理
function loadUserQuizRecord() {
    try {
        const savedRecord = localStorage.getItem('emergencyQuizRecord');
        if (savedRecord) {
            userQuizRecord = JSON.parse(savedRecord);

            // 检查是否为新的一天，重置答题次数
            const today = new Date().toISOString().split('T')[0];
            if (userQuizRecord.lastAttemptDate !== today) {
                userQuizRecord.dailyAttempts = 3;
                userQuizRecord.lastAttemptDate = today;
                saveUserQuizRecord();
            }
        } else {
            // 初始化新用户记录
            userQuizRecord.lastAttemptDate = new Date().toISOString().split('T')[0];
            saveUserQuizRecord();
        }
    } catch (error) {
        console.error('加载用户记录失败:', error);
    }
}

function saveUserQuizRecord() {
    try {
        localStorage.setItem('emergencyQuizRecord', JSON.stringify(userQuizRecord));
    } catch (error) {
        console.error('保存用户记录失败:', error);
    }
}

// 页面导航
function navigateTo(page) {
    document.querySelectorAll('main > section').forEach(section => {
        section.classList.add('hidden');
    });

    document.querySelectorAll('nav a').forEach(link => {
        link.classList.remove('nav-link-active');
    });

    const activeLink = document.querySelector(`a[href="#${page}"]`);
    if (activeLink) activeLink.classList.add('nav-link-active');

    const targetPage = document.getElementById(`${page}-page`);
    if (targetPage) {
        targetPage.classList.remove('hidden');
        switch (page) {
            case 'home':
                loadHomePage();
                break;
            case 'books':
                loadBooksPage();
                break;
            case 'quiz':
                if (currentQuiz.questions.length === 0) {
                    navigateTo('home');
                    alert('请先从首页开始答题');
                } else {
                    renderCurrentQuestion();
                }
                break;
        }
    }

    window.history.pushState(null, '', `#${page}`);
}

// 页面加载函数
function loadHomePage() {
    updateStats();
    loadWrongQuestions();
    document.getElementById('daily-attempts').innerHTML = `今日剩余答题次数: <span class="font-bold">${userQuizRecord.dailyAttempts}</span>`;
}

function updateStats() {
    const statsContainer = document.getElementById('stats-container');
    statsContainer.innerHTML = '';

    const totalAttempts = Math.floor(userQuizRecord.totalCount / 3);
    const accuracy = userQuizRecord.totalCount > 0 ?
        Math.round((userQuizRecord.correctCount / userQuizRecord.totalCount) * 100) : 0;

    const stats = [
        { icon: 'fa-calendar-check-o', title: '总答题次数', value: totalAttempts },
        { icon: 'fa-check-circle', title: '正确率', value: `${accuracy}%` },
        { icon: 'fa-question-circle', title: '总错题数', value: userQuizRecord.wrongQuestions.length },
        { icon: 'fa-trophy', title: '今日剩余次数', value: userQuizRecord.dailyAttempts }
    ];

    stats.forEach(stat => {
        const statCard = document.createElement('div');
        statCard.className = 'bg-white rounded-lg shadow-sm p-6 text-center';
        statCard.innerHTML = `
            <div class="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fa ${stat.icon} text-primary text-xl"></i>
            </div>
            <h3 class="text-xl font-bold mb-2">${stat.title}</h3>
            <p class="text-2xl font-bold text-primary">${stat.value}</p>
        `;
        statsContainer.appendChild(statCard);
    });
}

function loadWrongQuestions() {
    const wrongQuestionsContainer = document.getElementById('wrong-questions-container');

    if (userQuizRecord.wrongQuestions.length === 0) {
        wrongQuestionsContainer.innerHTML = `
            <div class="text-center py-8">
                <i class="fa fa-smile-o text-gray-400 text-4xl mb-4"></i>
                <p class="text-gray-600">暂无错题记录，继续加油！</p>
            </div>
        `;
        return;
    }

    wrongQuestionsContainer.innerHTML = '';

    // 显示最近3道错题
    const recentWrongQuestions = userQuizRecord.wrongQuestions.slice(-3).reverse();

    recentWrongQuestions.forEach(questionId => {
        const question = QuizBank.getQuestionById(questionId);
        if (question) {
            const questionCard = document.createElement('div');
            questionCard.className = 'border border-gray-200 rounded-lg p-4';
            questionCard.innerHTML = `
                <div class="flex items-start mb-4">
                    <div class="w-8 h-8 bg-danger/10 rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                        <i class="fa fa-times text-danger"></i>
                    </div>
                    <h3 class="font-bold">${question.question}</h3>
                </div>
                <div class="mb-4">
                    <p class="text-gray-600 mb-2">正确答案:</p>
                    <p class="bg-success/10 text-success p-3 rounded-lg">${question.options[question.correctAnswer]}</p>
                </div>
                <div>
                    <p class="text-gray-600 mb-2">解析:</p>
                    <p class="text-gray-800">${question.explanation}</p>
                </div>
            `;
            wrongQuestionsContainer.appendChild(questionCard);
        }
    });

    if (userQuizRecord.wrongQuestions.length > 3) {
        const moreButton = document.createElement('div');
        moreButton.className = 'text-center mt-4';
        moreButton.innerHTML = `
            <button class="btn-outline py-2 px-4" onclick="showAllWrongQuestions()">
                查看全部错题 <i class="fa fa-angle-right ml-1"></i>
            </button>
        `;
        wrongQuestionsContainer.appendChild(moreButton);
    }
}

function showAllWrongQuestions() {
    alert('功能开发中，敬请期待');
}

function loadBooksPage() {
    const booksContainer = document.getElementById('books-container');
    booksContainer.innerHTML = `
        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <img src="https://picsum.photos/seed/emergency1/400/300" alt="应急防护知识大全" class="w-full h-48 object-cover">
            <div class="p-4">
                <h3 class="font-bold text-lg mb-2">应急防护知识大全</h3>
                <p class="text-gray-600 mb-3">全面介绍各类紧急情况的应对方法和防护措施</p>
                <div class="flex justify-between items-center">
                    <span class="text-primary font-bold">¥39.90</span>
                    <button class="btn-primary py-1 px-3 text-sm">购买</button>
                </div>
            </div>
        </div>
    `;
}

// 答题流程
async function startQuiz() {
    if (userQuizRecord.dailyAttempts <= 0) {
        alert('今日答题次数已用完，明天再来吧！');
        return;
    }

    // 确保题库中有足够题目
    if (QuizBank.getTotalQuestionsCount() < 3) {
        const success = await QuizBank.loadQuestions(['advanced']);
        if (!success || QuizBank.getTotalQuestionsCount() < 3) {
            alert('题库题目不足，请稍后再试');
            return;
        }
    }

    // 准备题目
    showLoading('正在准备题目...');
    currentQuiz.questions = QuizBank.getRandomQuestions(3);
    currentQuiz.answers = Array(3).fill(null);
    currentQuiz.currentQuestionIndex = 0;

    // 显示答题页
    navigateTo('quiz');
    renderCurrentQuestion();
    hideLoading();
}

function renderCurrentQuestion() {
    const question = currentQuiz.questions[currentQuiz.currentQuestionIndex];
    const container = document.getElementById('quiz-question-container');

    if (!question) {
        console.error('问题不存在');
        return;
    }

    container.innerHTML = `
        <div class="bg-gray-50 p-6 rounded-lg">
            <h3 class="text-xl font-bold mb-4">${question.question}</h3>
            ${question.options.map((option, index) => `
                <label class="quiz-option block mb-2">
                    <input type="radio" name="answer" value="${index}" ${currentQuiz.answers[currentQuiz.currentQuestionIndex] === index ? 'checked' : ''}>
                    <span>${option}</span>
                </label>
            `).join('')}
        </div>
    `;

    // 更新问题进度
    const currentQuestionNum = document.getElementById('current-question-num');
    const totalQuestions = document.getElementById('total-questions');
    currentQuestionNum.textContent = currentQuiz.currentQuestionIndex + 1;
    totalQuestions.textContent = currentQuiz.questions.length;

    // 更新按钮状态
    const prevButton = document.getElementById('prev-btn');
    const nextButton = document.getElementById('next-btn');
    prevButton.disabled = currentQuiz.currentQuestionIndex === 0;
    if (currentQuiz.currentQuestionIndex === currentQuiz.questions.length - 1) {
        nextButton.textContent = '提交';
    } else {
        nextButton.textContent = '下一题';
    }
}

function prevQuestion() {
    if (currentQuiz.currentQuestionIndex > 0) {
        saveAnswer();
        currentQuiz.currentQuestionIndex--;
        renderCurrentQuestion();
    }
}

function nextQuestion() {
    saveAnswer();
    if (currentQuiz.currentQuestionIndex < currentQuiz.questions.length - 1) {
        currentQuiz.currentQuestionIndex++;
        renderCurrentQuestion();
    } else {
        // 提交答案
        submitQuiz();
    }
}

function saveAnswer() {
    const selectedOption = document.querySelector('input[name="answer"]:checked');
    if (selectedOption) {
        currentQuiz.answers[currentQuiz.currentQuestionIndex] = parseInt(selectedOption.value);
    }
}

function submitQuiz() {
    let correctCount = 0;
    currentQuiz.questions.forEach((question, index) => {
        if (currentQuiz.answers[index] === question.correctAnswer) {
            correctCount++;
        } else {
            if (!userQuizRecord.wrongQuestions.includes(question.id)) {
                userQuizRecord.wrongQuestions.push(question.id);
            }
        }
    });

    // 更新用户测验记录
    userQuizRecord.correctCount += correctCount;
    userQuizRecord.totalCount += currentQuiz.questions.length;
    userQuizRecord.dailyAttempts--;
    saveUserQuizRecord();

    // 显示结果
    const resultElement = document.getElementById('result');
    resultElement.textContent = `你答对了 ${correctCount} 道题，共 ${currentQuiz.questions.length} 道题。`;
    resultElement.style.display = 'block';

    // 返回首页
    navigateTo('home');
}

// 导出函数，以便在其他文件中使用
export {
    loadUserQuizRecord,
    startQuiz,
    navigateTo
};